package myLearnjdk.jdk.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 高效文件内存映射
 * 
 * MappedByteBuffer是jdk的nio下提供的一个类 用与高效读取超大文件
 * 效率远高于传统的阻塞式io流
 * 
 * @author yangcheng  
 * @date 2018年12月24日  
 * @version V1.0
 */
public class MappedByteBufferTest {
	public static void main(String[] args) throws Exception {  
		
		/**
		 * 通过阻塞io的getChannel获取到文件的通道FileChannel对象
		 */
		FileChannel finc = new FileInputStream("F:\\我们结婚啦.mp4").getChannel();  
        FileChannel foutc = new FileOutputStream("F:\\a.mp4").getChannel();  
        
        long timeStar = System.currentTimeMillis();// 得到当前的时间 
        
        MappedByteBuffer mbb = finc.map(FileChannel.MapMode.READ_ONLY, 0, finc.size());  
        System.out.println(finc.size()/1024+"KB");  
        long timeEnd = System.currentTimeMillis();// 得到当前的时间  
        
        System.out.println("Read time :" + (timeEnd - timeStar) + "ms");  
        
        timeStar = System.currentTimeMillis();  
        foutc.write(mbb);//2.写入  
        mbb.flip();  
        timeEnd = System.currentTimeMillis();  
        
        System.out.println("Write time :" + (timeEnd - timeStar) + "ms");  
        finc.close();  
        finc.close();  
        
        
        /**
         * 释放FileChannel获取到的文件句柄
         */
        Method getCleanerMethod = mbb.getClass().getMethod("cleaner", new Class[0]);  
        getCleanerMethod.setAccessible(true);  
        sun.misc.Cleaner cleaner = (sun.misc.Cleaner)   
        getCleanerMethod.invoke(mbb, new Object[0]);  
        cleaner.clean();  
    }  

}
